package com.lovo.jwt;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.lovo.utile.dto.UserDto;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

public class CreateJWT {
    private  static final  long EXPIRE_TIME=1000*30*100;
    private static  final  String TOKEN_SECRET="J177";

    public static String getToken(UserDto userDto){
        //过期时间
        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        //私钥及加密算法
        Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
        //设置头信息
        HashMap<String, Object> header = new HashMap<>(2);
        header.put("typ", "JWT");
        header.put("alg", "HS256");
        //附带username和userID生成签名

        String token= JWT.create().withHeader(header)
                .withClaim("userName",userDto.getUserName())
                .withClaim("password",userDto.getPassword())
//                .withClaim("power",userDto.getPower())
                .withExpiresAt(date).sign(algorithm);
        return  token;

    }

    public static DecodedJWT verifyToken(String token){
        boolean bl=true;
        //私钥及加密算法
        Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
        //构建认证对象
        JWTVerifier verifier = JWT.require(algorithm).build();
        DecodedJWT jwt = null;
        try {
            //认证  ,认证失败抛出异常
             jwt = verifier.verify(token);
               //拿到token中的内容
            System.out.println(jwt.getClaim("userName").asString());
            System.out.println(jwt.getClaim("password").asString());
//            System.out.println(jwt.getClaim("power").asList(String.class));
        }catch (Exception e){
            bl=false;
        }
        return  jwt;
    }

    public static void main(String[] args) {
    }
}
